package de.fhwgt.quiz.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import de.fhwgt.quiz.error.QuizError;

/**
 * Servlet implementation class WebQuiz
 */
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Quiz quiz;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogoutServlet() {
        super();
        quiz = Quiz.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 * @see doPost
	 * macht das selbe wie doPost 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 * Username wird über einen HTTP-Post request übergeben.
	 * Wenn erfolgreich return -> 0
	 * Wenn Fehlgeschlagen -> 1 + errordcode + errormessage
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		QuizError error = new QuizError();
		if (request.getParameter("user")!=null){
	        String user = request.getParameter("user");
	        for(Player p:quiz.getPlayerList()){
	        	if(p.getName().equals(user)){
	        		System.out.println(":::LoginServlet:: Removing Player: "+p.getName());
	        		this.quiz.removePlayer(p, error);
	        		if(!error.isSet()){
	        			this.quiz.signalPlayerChange();
	        		}
	        	}
	        }
	    }	
	}

}
